<?php

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 订单模型
 */
class Order extends Model
{
    // 追加属性
    protected $append = [
        'order_status_text',
        'pay_status_text',
        'type_text',
//        'pay_time_text',
        'deleted_text',
        'shipping_status_text',
        'order_prom_type_text',
        'item_text'
    ];

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id');
    }

    public function goods()
    {
        return $this->belongsTo('Goods', 'goods_id', 'id')->field('id,name,shop_price,market_price,image');
    }

    public function address()
    {
        return $this->belongsTo('Address', 'address_id', 'id');
    }

    public function getOrderStatusList()
    {
        return ['0' => __('Order_status 0'), '1' => __('Order_status 1'), '2' => __('Order_status 2'), '3' => __('Order_status 3'), '4' => __('Order_status 4'), '5' => __('Order_status 5')];
    }

    public function getPayStatusList()
    {
        return ['0' => __('Pay_status 0'), '1' => __('Pay_status 1'), '2' => __('Pay_status 2'), '3' => __('Pay_status 3'), '4' => __('Pay_status 4')];
    }

    public function getTypeList()
    {
        return ['0' => __('Type 0'), '1' => __('Type 1'), '2' => __('Type 2')];
    }

    public function getDeletedList()
    {
        return ['1' => __('Deleted 1'), '0' => __('Deleted 0')];
    }

    public function getShippingStatusList()
    {
        return ['0' => __('Shipping_status 0'), '1' => __('Shipping_status 1')];
    }

    public function getOrderPromTypeList()
    {
        return ['0' => __('Order_prom_type 0'), '1' => __('Order_prom_type 1'), '2' => __('Order_prom_type 2'), '3' => __('Order_prom_type 3'), '4' => __('Order_prom_type 4')];
    }

    public function getGoodsNumList()
    {
        return ['4) unsigne' => __('4) unsigne')];
    }


    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['order_status'];
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['pay_status'];
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['pay_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDeletedTextAttr($value, $data)
    {
        $value = $value ? $value : $data['deleted'];
        $list = $this->getDeletedList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getShippingStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['shipping_status'];
        $list = $this->getShippingStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getOrderPromTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['order_prom_type'];
        $list = $this->getOrderPromTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getItemTextAttr($value, $data)
    {
        //规格
        $goodsAttrM = new GoodsAttr();
        $goodsAttr = $goodsAttrM->get($data['item_id']);
        $Attr = [];
        if ($goodsAttr) {
            $attrName = $goodsAttr->attr['name'];

            $Attr = [
                'id' => $goodsAttr['id'],
                'attr_name' => $attrName,
                'attr_value' => $goodsAttr['attr_value']
            ];
        }
        return $Attr;

    }


    /**
     * @param $params ['type'] 订单类型:0=自己买,1=送一人,2=群发多人抢
     * $params['address_id'] 地址
     * $params['item_id'] 商品规格id
     * $params['goods_id'] 商品id
     * $params['integral'] 使用积分
     * $params['num'] 数量
     * $params['order_prom_type'] 订单活动类型
     * $params['order_prom_id'] 订单活动id
     * $params['user_prom_id'] 用户参与活动id
     * $master_order_sn 购物车下单时传此参数
     *
     */
    public function addOrder($params, $master_order_sn = '')
    {
        $goods = Db::name('goods')->find($params['goods_id']);
        if ($goods['store_count'] - $params['num'] < 0) {
            return ['code' => 0, 'msg' => '商品库存不足', 'data' => ''];
        }
        //计算商品总价
        $priceInfo = $this->orderPrice($params);


        $params['goods_price'] = $priceInfo['goods_price'];
        $params['total_amount'] = $priceInfo['total_amount'];
        $params['createtime'] = time();
        if ($params['type'] == '1') {
            //送一人
            if (!empty($master_order_sn)) {
                //购物车下单
                $params['master_order_sn'] = $master_order_sn;
            }

            $params['order_sn'] = $this->order_number();
            $params['integral'] = $priceInfo['integral'];
            $params['goods_num'] = $params['num'];

            unset($params['num']);
            $order = self::create($params);
            if ($order) {
                if (!empty($master_order_sn)) {

                    $cartToOrder = $this->cartToOrder($master_order_sn);
                    //购物车下单
                    $data = [
                        'type' => '1',
                        'master_order_sn' => $master_order_sn,
                        'total_amount' => $cartToOrder
                    ];

                    $this->directPayOrder($data['total_amount'], $data['master_order_sn']);
                } else {
                    $data = [
                        'order_id' => $order->id,
                        'type' => '1',
                        'order_sn' => $order->order_sn,
                        'goods_id' => $order->goods_id,
                        'total_amount' => $order->total_amount
                    ];
                    $this->directPayOrder($data['total_amount'], $data['order_sn']);
                }


                return ['code' => 1, 'msg' => '下单成功', 'data' => $data];

            } else {
                return ['code' => 0, 'msg' => '下单失败', 'data' => ''];
            }


        } elseif ($params['type'] == '2') {
            //群发多人抢
//            $params['master_order_sn'] = 'master-' . $this->order_number();
            $params['master_order_sn'] = $this->order_number();
            if (!empty($master_order_sn)) {
                //购物车下单
                $params['master_order_sn'] = $master_order_sn;
            }

            $num = intval($params['num']);
            if (!is_numeric($num) || $num < 1) {
                return ['code' => 0, 'msg' => '参数错误', 'data' => ''];
            }

            unset($params['num']);

            $orderIds = [];
            $totalAmount = 0;
            for ($i = $num; $i > 0; $i--) {
                $params['order_sn'] = $this->order_number();
//                $params['goods_price'] = $goodsInfo['shop_price'];
                $params['goods_price'] = $priceInfo['real_price'];//商品总价

                $params['total_amount'] = ($params['goods_price'] * 100 - $params['integral'] * 100) / 100;
                $params['goods_num'] = 1;
                $order = self::create($params);
                array_push($orderIds, $order->id);
                $totalAmount = ($totalAmount * 100 + $order->total_amount * 100) / 100;
            }

            if ($order) {

                if (!empty($master_order_sn)) {
                    //购物车下单
                    $cartToOrder = $this->cartToOrder($master_order_sn);
                    //购物车下单
                    $data = [
//                        'order_id' => $order->id,
                        'type' => '2',
                        'master_order_sn' => $master_order_sn,
//                        'order_sn' => $order->order_sn,
//                        'goods_id' => $order->goods_id,
                        'total_amount' => $cartToOrder
                    ];

                    $this->directPayOrder($data['total_amount'], $data['master_order_sn']);
                } else {
                    $data = [
                        'order_id' => $orderIds,
                        'type' => '2',
                        'master_order_sn' => $params['master_order_sn'],
                        'goods_id' => $params['goods_id'],
                        'total_amount' => $totalAmount
                    ];
                    $this->directPayOrder($data['total_amount'], $data['master_order_sn']);
                }


                return ['code' => 1, 'msg' => '下单成功', 'data' => $data];

            } else {
                return ['code' => 0, 'msg' => '下单失败', 'data' => ''];
            }

        } else {
            //自己买
            if (!empty($master_order_sn)) {
                //购物车下单
                $params['master_order_sn'] = $master_order_sn;
            }

            $params['order_sn'] = $this->order_number();
            $params['integral'] = $priceInfo['integral'];
            $params['goods_num'] = $params['num'];

            unset($params['num']);
            $order = self::create($params);
            if ($order) {
                if (!empty($master_order_sn)) {

                    $cartToOrder = $this->cartToOrder($master_order_sn);
                    //购物车下单
                    $data = [
                        'type' => '0',
                        'master_order_sn' => $master_order_sn,
                        'total_amount' => $cartToOrder
                    ];

                    $this->directPayOrder($data['total_amount'], $data['master_order_sn']);
                } else {
                    $data = [
                        'order_id' => $order->id,
                        'type' => '0',
                        'order_sn' => $order->order_sn,
                        'goods_id' => $order->goods_id,
                        'total_amount' => $order->total_amount
                    ];
                    $this->directPayOrder($data['total_amount'], $data['order_sn']);
                }

                return ['code' => 1, 'msg' => '下单成功', 'data' => $data];

            } else {
                return ['code' => 0, 'msg' => '下单失败', 'data' => ''];
            }

        }
    }


    //生成订单号
    public function order_number()
    {
        $data = date('Ymd', time()) . time() . rand(10, 99);//18位
        // return md5($openid.time().rand(10,99));//32位
        return $data;
    }

    /**
     * 计算商品价格
     */
    public function orderPrice($params)
    {
        $goodsInfo = Db::name('goods')->where(['id' => $params['goods_id']])->find();
        $data = [];
        if ($params['order_prom_type'] == '1') {
            //砍价
            //计算商品总价

            $real_price = Db::name('cutdown_follow')->where(['id' => $params['user_prom_id']])->value('deal_price'); //砍价活动最终成交价

            $data = [
                'real_price' => $real_price, //群发多人抢时，商品单价
                'goods_price' => $real_price, //商品总价
                'integral' => 0, //订单使用积分，活动商品不使用积分
                'total_amount' => $real_price //订单金额
            ];

        } elseif ($params['order_prom_type'] == '2') {
            //拼团
            //计算商品总价
            $real_price = Db::name('team_activity')->where(['id' => $params['order_prom_id']])->value('team_price');
            $goods_price = ($real_price * 100 * $params['num']) / 100;
            $total_amount = $goods_price;

            $data = [
                'real_price' => $real_price,
                'goods_price' => $goods_price,
                'integral' => 0,
                'total_amount' => $total_amount
            ];

        } elseif ($params['order_prom_type'] == '3') {
            //秒杀
            $price = Db::name('flash_sale')->where(['id' => $params['order_prom_id']])->value('price');
            $data = [
                'real_price' => $price,
                'goods_price' => $price,
                'integral' => 0,
                'total_amount' => $price
            ];


        } elseif ($params['order_prom_type'] == '4') {
            //促销
            $goodsM = new \app\common\model\Goods;
            $goods = $goodsM->get($params['goods_id']);
            $promGoodsLogic = new \app\common\logic\PromGoodsLogic($goods);
            $price = $promGoodsLogic->getPromotionPrice($goodsInfo['shop_price']);

            $data = [
                'real_price' => $price,
                'goods_price' => ($price * 100 * intval($params['num'])) / 100,
                'integral' => 0,
                'total_amount' => ($price * 100 * intval($params['num'])) / 100
            ];


        } else {
            //普通商品
            //计算商品总价
            $data['real_price'] = $goodsInfo['shop_price'];
            $data['goods_price'] = ($goodsInfo['shop_price'] * 100 * intval($params['num'])) / 100;
            $data['integral'] = $params['integral'] * intval($params['num']);
            $data['total_amount'] = ($data['goods_price'] * 100 - $data['integral'] * 100) / 100;
        }

        return $data;
    }


    /**
     * 购物车下单金额
     * @param $master_order_sn
     * @return int|mixed|string
     */
    public function cartToOrder($master_order_sn)
    {
        //    先查看一下 是不是 合并支付的主订单号
        $order_list = Db::name('order')->where("master_order_sn", $master_order_sn)->select();

        $total_amount = 0;
        if ($order_list) {

            foreach ($order_list as $key => $val) {
                $amount = Db::name('order')->where('id', $val['id'])->value('total_amount');
                $total_amount += $amount * 100;
            }

            $total_amount = number_format($total_amount / 100, 2, '.', '');


        }
        return $total_amount;
    }

    public function directPayOrder($total_amount, $order_sn)
    {

        if ($total_amount == 0) {
            update_pay_status($order_sn);
        }
    }


}